package com.xtkj.superclub_shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xtkj.commons.JsonResult;
import com.xtkj.commons.SnowflakeIdWorker;
import com.xtkj.superclub_entity.entity.activity.AlipayBean;
import com.xtkj.superclub_entity.entity.shop.*;
import com.xtkj.superclub_entity.entity.user.User;
import com.xtkj.superclub_shop.client.IPayClient;
import com.xtkj.superclub_shop.dao.*;
import com.xtkj.superclub_shop.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lizheqi
 * @create 2019-12-28-11:59
 */
@Service
@Transactional
public class CartServiceImpl implements ICartService {
    @Autowired
    private IProDao proDao;
    @Autowired
    private ICartDao cartDao;
    @Autowired
    private IOrderDao orderDao;
    @Autowired
    private IColorDao colorDao;
    @Autowired
    private ISizeDao sizeDao;
    @Autowired
    private IAddressDao addressDao;
    @Autowired
    private IProColorSizeDao proColorSizeDao;
    @Autowired
    private IOrderProductDao orderProductDao;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private IPayClient payClient;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 将商品列项添加到购物车
     * @param proItem
     */
    @Override
    public void addProToCart(ProItem proItem) {
        String userId = proItem.getUserId();
        String proId = proItem.getProId();
        String colorId = proItem.getColorId();
        String sizeId = proItem.getSizeId();
        String pcs = proId+"-"+colorId+"-"+sizeId;
        int cnt = proItem.getCnt();
        HashOperations<String, String, Integer> ops= redisTemplate.opsForHash();
        Boolean hasKey = ops.hasKey(userId, pcs);
        //判断缓存里面是否有用户键以及组合键
        if(!hasKey){
            ops.put(userId,pcs,cnt);
        }else{
            Integer newCnt =  ops.get(userId,pcs)+cnt;
            proItem.setCnt(newCnt);
            ops.put(userId,pcs,newCnt);
        }
        //存入到缓存后将数据存放到数据库
        //QueryWrapper<ProItem> wrapper = new QueryWrapper<>();
        //先查询数据库里面有没有该类型的商品
        //wrapper.eq("pro_id",proId).eq("color_id",colorId).eq("size_id",sizeId).eq("user_id",userId);
        //ProItem dbProItem = cartDao.selectOne(wrapper);
        //if(dbProItem!=null){
            //dbProItem.setCnt(ops.get(userId,pcs));
            //对数据库进行修改操作
            //cartDao.updateById(dbProItem);
        //}else {
            //对数据库进行插入操作
            //cartDao.insert(proItem);
        //}
    }

    /**
     * 显示购物车详情
     * @param userId
     * @return
     */
    @Override
    public List<ProItem> shopCartListInfo(String userId) {
        //从数据库里面查询该用户对应的商品列项集合
        HashOperations ops = redisTemplate.opsForHash();
        Map map = ops.entries(userId);
        List<ProItem> proItemList = new ArrayList<ProItem>();
        for(Object key:map.keySet()){
            //key "proId-colorId-sizeId"
            String[] strs = key.toString().split("-");
            Product product = proDao.selectById(strs[0]);
            Color color = colorDao.selectById(strs[1]);
            Size size = sizeDao.selectById(strs[2]);
            //通过proId、colorId、sizeId查询proItemId
            //QueryWrapper<ProItem> wrapper = new QueryWrapper<>();
            //wrapper.eq("pro_id",strs[0]).eq("color_id",strs[1]).eq("size_id",strs[2]).eq("user_id",userId);
            //ProItem proItem = cartDao.selectOne(wrapper);
            ProItem proItem = new ProItem();
            proItem.setProItemId(snowflakeIdWorker.nextId()+"");
            //从redis里面获取该类型商品所有数量
            int cnt = Integer.valueOf(map.get(key).toString());
            proItem.setProduct(product).setColor(color).setSize(size).setCnt(cnt);
            proItemList.add(proItem);
        }
        return proItemList;
    }

    /**
     * 从购物车里面删除某类商品
     * @param proItem
     */
    @Override
    public void deleteShopCartCommodity(ProItem proItem) {
        HashOperations ops = redisTemplate.opsForHash();
        String userId = proItem.getUserId();
        String proId = proItem.getProId();
        String colorId = proItem.getColorId();
        String sizeId = proItem.getSizeId();
        String pcs = proId+"-"+colorId+"-"+sizeId;
        Boolean flag = ops.hasKey(userId, pcs);
        if(flag){
            //先从缓存里面删除该种类型的商品
            ops.delete(userId,pcs);
            //从数据库里面删除该种类型的商品
            //UpdateWrapper<ProItem> wrapper = new UpdateWrapper<>();
            //wrapper.eq("pro_id",proId).eq("color_id",colorId).eq("size_id",sizeId).eq("user_id",userId);
            //cartDao.delete(wrapper);
}
    }

    /**
     * 清空购物车
     * @param userId
     */
    @Override
    public void cleanShopCartList(String userId) {
        HashOperations ops = redisTemplate.opsForHash();
        Map map = ops.entries(userId);
        for (Object key:map.keySet()){
            //删除购物车缓存
            ops.delete(userId,key);
        }
        //对数据库里面的该用户对应的的购物车表清空
        //UpdateWrapper<ProItem> wrapper= new UpdateWrapper<>();
        //wrapper.eq("user_id",userId);
        //cartDao.delete(wrapper);
    }

    /**
     * 结算购物车
     * @param
     */
    @Override
    public void checkoutShopCart(User user,Address address) {
        String userId = user.getUserId();
        HashOperations ops = redisTemplate.opsForHash();
        Map map = ops.entries(userId);
        double totalPrice = 0;
        int totalCnt = 0;
        for (Object key:map.keySet()){
            //key "proId-colorId-sizeId"
            String[] strs = key.toString().split("-");
            String proId = strs[0];
            String colorId = strs[1];
            String sizeId = strs[2];
            //通过proId查询商品的单价
            Product product = proDao.selectById(proId);
            Integer cnt = Integer.valueOf(ops.get(userId, key).toString());
            totalPrice += cnt * product.getPrice();
            totalCnt += cnt;
        }
        //先对订单表里面填入数据
        Order order = new Order();
        order.setOrderId(snowflakeIdWorker.nextId()+"").setUserId(userId).setUserName(user.getNickName()).setUserName(user.getNickName()).setOrderStatus(0).setTotal(totalPrice).setOrderDt(new Date()).setAddressId(address.getAddressId());
        orderDao.insert(order);
        //插入完成后对订单商品表插入数据
        OrderProductMap orderProduct = new OrderProductMap();
        for (Object key:map.keySet()){
            //key "proId-colorId-sizeId"
            String[] strs = key.toString().split("-");
            String proId = strs[0];
            String colorId = strs[1];
            String sizeId = strs[2];
            Product product = proDao.selectById(proId);
            //对订单商品表进行插入
            orderProduct.setId(snowflakeIdWorker.nextId()+"").setProId(proId).setColorId(colorId).setSizeId(sizeId).setOrderId(order.getOrderId()).setPrice(product.getPrice()).setCnt(Integer.valueOf(ops.get(userId,key).toString()));
            orderProductDao.insert(orderProduct);
            //并且对商品属性表里面的库存进行修改
            UpdateWrapper<ProColorSizeMap> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("pro_id",proId).eq("color_id",colorId).eq("size_id",sizeId);
            //先查询是否有该对象
            QueryWrapper<ProColorSizeMap> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pro_id",proId).eq("color_id",colorId).eq("size_id",sizeId);
            ProColorSizeMap proColorSizeMap = proColorSizeDao.selectOne(queryWrapper);
            if(proColorSizeMap!=null){
                proColorSizeMap.setCnt(proColorSizeMap.getCnt()-Integer.valueOf(ops.get(userId,key).toString()));
                //对数据库里面的库存数量进行修改
                proColorSizeDao.update(proColorSizeMap,updateWrapper);
            }
        }
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(order.getOrderId()).setTotal_amount(order.getTotal()+"").setSubject(order.getOrderId());
        //调用支付接口
        JsonResult jsonResult = payClient.alipay(alipayBean);
        String alipay = jsonResult.getMsg();
        if("支付成功".equals(alipay)){
            order.setType("支付宝").setOrderStatus(1);
        }else{
            order.setType("支付宝").setOrderStatus(0);
        }
        //订单更新
        orderDao.updateById(order);
        //清空购物车
        cleanShopCartList(userId);
    }

    /**
     * 支付完成后的操作
     * @param userId
     * @param order
     */
    @Override
    public void pay(String userId, Order order) {
        //将订单的状态变为1为已支付状态
        order.setOrderStatus(1).setType("支付宝");
        orderDao.updateById(order);
    }


}
